-module(phone_fsm_handler).
-export([init/1, terminate/1, handle_event/2]).
-export([idle/0]).

init([]) ->
    spawn(?MODULE, idle, []).    

terminate(FSMPid) ->
    FSMPid ! stop.

handle_event({_Action, _Id, Event}, FSMPid) ->
    FSMPid ! Event.

idle() ->
    receive
	{Number, incoming} ->
	    start_ringing(),
	    ringing(Number);
	off_hook ->
	    start_tone(),
	    dial();
	stop ->
	    ok
    end.

ringing(Number) ->
    receive
	{Number, other_on_hook} ->
	    stop_ringing(),
	    idle();
	{Number, off_hook} ->
	    stop_ringing(),
	    connected(Number);
	stop -> 
	    ok
    end.

connected(Number) ->
    receive
	{Number, on_hook} ->
	    idle();
	stop -> 
	    ok
    end.

dial() ->
    receive
	{_Number, on_hook} ->
	    idle();
	stop ->
	    ok;
	{Number, _Other} ->
	    connected(Number)
    end.

start_ringing() ->
    io:format("start ringing").

start_tone() ->
    io:format("start tone").

stop_ringing() ->
    io:format("stop ringing").
